// pages/articleList/index.ts
const app = getApp<IAppOption>()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    apiUrl: app.globalData.apiUrl,
    category_id: 0,
    page: 1,
    page_size: 9,
    current_page: 1,
    last_page: 0,
    articles: [],
    title: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(opetion: any) {
    let category_id: number = opetion.category;
    this.getArticles(category_id, this.data.page, this.data.page_size);
    this.setData({
      title: opetion.title,
      category_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  getArticles(category_id: number, page: number, page_size: number) {
    let that = this;
    wx.request({
      url: app.globalData.apiUrl + 'api/article/' + category_id + '/list',
      data: {
        page: page,
        page_size: page_size
      },
      success: function (res: any) {
        if (res.data.code == 0) {
          let arr: Array = []
          if (!res.data.data.data.length) {
            return
          }
          res.data.data.data.forEach(function (item: any) {
            arr.push(item)
          })
          that.setData({
            category_id: category_id,
            articles: that.data.articles.concat(arr),
            last_page: res.data.data.last_page,
            current_page: res.data.data.current_page
          })
        }
      }
    })
  },
  toArticleDetail(e: any) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../articleDetail/index?id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    debugger
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    debugger
    let page = this.data.current_page + 1
    this.getArticles(this.data.category_id, page, this.data.page_size)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

export default app